package im.composer.media.audio.stream;

import java.io.IOException;
import java.io.OutputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;

import lowlevel.LameEncoder;

import org.tritonus.share.sampled.file.AudioOutputStream;

public class LameOutputStream extends LameEncoder implements AudioOutputStream {

	private final OutputStream out;
	private byte[] buf = new byte[getPCMBufferSize()];

	public LameOutputStream(OutputStream out) {
		this.out = out;
	}

	public AudioFormat getFormat() {
		return getSourceFormat();
	}

	public long getLength() {
		return AudioSystem.NOT_SPECIFIED;
	}

	@Override
	public void close() {
		int len = encodeFinish(buf);
		try {
			out.write(buf, 0, len);
		} catch (IOException e) {
		}
		super.close();
		try {
			out.flush();
		} catch (IOException e) {
		}
		try {
			out.close();
		} catch (IOException e) {
		}
	}

	public int write(byte[] abData, int nOffset, int nLength) throws IOException {
		int len = encodeBuffer(abData, nOffset, nLength, buf);
		out.write(buf, 0, len);
		return len;
	}
}
